package com.baibei.product.merge.detail;

import android.content.Context;
import android.text.TextUtils;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.AddressInfo;
import com.baibei.model.MergeOrderInfo;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.Empty;
import com.rae.swift.Rx;

import java.util.List;

/**
 * Created by ChenRui on 2017/8/15 0015 18:58.
 */
public class MergeOrderDetailPresenterImpl extends BasicPresenterImpl<MergeOrderDetailContract.View> implements MergeOrderDetailContract.Presenter {
    ITradeApi mTradeApi;
    IUserApi mUserApi;

    public MergeOrderDetailPresenterImpl(Context context, MergeOrderDetailContract.View view) {
        super(context, view);
        mTradeApi = ApiFactory.getInstance().getTradeApi();
        mUserApi = ApiFactory.getInstance().getUserApi();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void start() {
        super.start();
        createObservable(mUserApi.getAddress("1"))
                .subscribe(new ApiDefaultObserver<List<AddressInfo>>() {
                    @Override
                    protected void onError(String s) {
                    }

                    @Override
                    protected void accept(List<AddressInfo> data) {
                        if (Rx.isEmpty(data)) return;
                        mView.onLoadAddress(data.get(0));
                    }
                });
    }

    @Override
    public void merge() {
        if (!checkParams()) {
            return;
        }

        MergeOrderInfo m = mView.getMergeOrderInfo();

        createObservable(mTradeApi.createMergeOrder(m.getProductId(), m.getName(), mView.getQuantity(), m.getCrawdPrice(), mView.getAddress()))
                .subscribe(new ApiDefaultObserver<Empty>() {
                    @Override
                    protected void onError(String s) {
                        mView.onMergeFailed(s);
                    }

                    @Override
                    protected void accept(Empty empty) {
                        mView.onMergeSuccess();
                    }
                });
    }

    @Override
    public boolean checkParams() {
        MergeOrderInfo m = mView.getMergeOrderInfo();
        if (m == null) {
            mView.onMergeFailed("拼单信息不存在");
            return false;
        }
        int quantity = mView.getQuantity();
        String address = mView.getAddress();

        if (quantity <= 0) {
            mView.onMergeFailed("请输入拼单数量");
            return false;
        }
        if (TextUtils.isEmpty(address)) {
            mView.onMergeFailed("请输入收货地址");
            return false;
        }
        return true;
    }

}
